﻿using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.Threading;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.BusinessLogic.NotifyMessageService;
using FileManager_Client.Utility;
using WHC.WareHouseMis.UI;
using BaseExceptionEnum = FileManager_Client.BusinessLogic.FileManagerUserService.BaseExceptionEnum;

namespace FileManager_Client.PresentationLayer
{
    public partial class Login : Form
    {
        #region From Constructor
        private WaitDialogForm _waitBeforeLogin;
        private readonly UserService _userService;
        private MainForm mainForm;
        private ToolTip loginNameTip = new ToolTip();
        private static object lockObj = new object();
        public Login()
        {
            InitializeComponent();
            if (null == CacheGlobal.GetCache(GlobalString.System_Config_String.Wcf_FileServiceCacheKey))
                CacheGlobal.Add(GlobalString.System_Config_String.Wcf_FileServiceCacheKey, new FileManager_UserServiceClient());
            skinEngine1.SkinFile = GlobalString.System_Config_String.SkinFileString;
            StartPosition = FormStartPosition.CenterScreen;
            _userService = new UserService();
            _userService.OnCompletedEvent += userService_OnCompletedEvent;
            _userService.OnGetComapnyCollectionComplatedEvent += _userService_OnGetComapnyCollectionComplatedEvent;
            _userService.OnGetFolderCollectionComplatedEvent += _userService_OnGetFolderCollectionComplatedEvent;
            _userService.OnGetFolderRoleCollectionComplatedEvent += _userService_OnGetFolderRoleCollectionComplatedEvent;
            loginNameTip.AutoPopDelay = 5000;
            loginNameTip.InitialDelay = 1000;
            loginNameTip.ReshowDelay = 500;
            loginNameTip.ShowAlways = true;
            loginNameTip.IsBalloon = true;
            loginNameTip.ToolTipIcon = ToolTipIcon.Info;
            loginNameTip.Active = true;
            loginNameTip.ToolTipTitle = "输入提示:";
        }
        #endregion

        #region User service event
        void _userService_OnGetFolderRoleCollectionComplatedEvent(object sender, GetFolderRoleEventArgs e)
        {
            var result = e.Result;
            var messageStr = e.Error;
            if (null != result)
                messageStr = ResultEnumMessage(result.ResultExceptionk__BackingField);
            if (!(string.IsNullOrEmpty(messageStr)))
                AsynShowMessage(messageStr);
            else
            {
                CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, result);
                if (_waitBeforeLogin.IsHandleCreated)
                    _waitBeforeLogin.BeginInvoke((EventHandler)delegate { _waitBeforeLogin.Close(); });
                else
                    _waitBeforeLogin.Invoke((EventHandler)delegate { _waitBeforeLogin.Close(); });
                //  BeginInvoke((EventHandler)delegate
                //   {
                txtLoginName.Text = "";
                txtPwd.Text = "";
                mainForm = new MainForm(this);
                mainForm.Show();
                //    });

            }
        }

        void _userService_OnGetFolderCollectionComplatedEvent(object sender, GetFolderEventArgs e)
        {
            var result = e.Result;
            var messageStr = e.Error;
            if (null != result)
                messageStr = ResultEnumMessage(result.ResultExceptionk__BackingField);
            if (!(string.IsNullOrEmpty(messageStr)))
                AsynShowMessage(messageStr);
            else
            {
                _waitBeforeLogin.BeginInvoke((EventHandler)delegate { _waitBeforeLogin.Caption = GlobalString.System_Config_String.LoginPassLoadingFolderRoleStr; });
                CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, result);
                _userService.GetFolderRoleService();
            }
        }

        void _userService_OnGetComapnyCollectionComplatedEvent(object sender, GetComapnyEventArgs e)
        {
            var result = e.Result;
            var messageStr = e.Error;
            if (null != result)
                messageStr = ResultEnumMessage(result.ResultExceptionk__BackingField);
            if (!(string.IsNullOrEmpty(messageStr)))
                AsynShowMessage(messageStr);
            else
            {
                _waitBeforeLogin.BeginInvoke((EventHandler)delegate { _waitBeforeLogin.Caption = GlobalString.System_Config_String.LoginPassLoadingFolderStr; });
                CacheGlobal.Add(GlobalString.System_Config_String.CompanyCollectionCache, result);
                _userService.GetFolderService();
            }
        }

        void userService_OnCompletedEvent(object sender, LoginEventArgs e)
        {
            var result = e.Result;
            var messageStr = e.Error;
            if (null != result)
                messageStr = ResultEnumMessage(result.ResultExceptionk__BackingField);
            if (!(string.IsNullOrEmpty(messageStr)))
                AsynShowMessage(messageStr);
            else
            {
                if (result != null)
                {
                    CacheGlobal.Add(GlobalString.System_Config_String.UserSession, result);
                     lock (lockObj)
                     {
                         if (_waitBeforeLogin.InvokeRequired)
                             _waitBeforeLogin.BeginInvoke(
                                 (EventHandler)
                                 delegate
                                     { _waitBeforeLogin.Caption = GlobalString.System_Config_String.LoginPassLoadingStr;
                                     });
                         else
                             _waitBeforeLogin.Caption = GlobalString.System_Config_String.LoginPassLoadingStr;
                     }
                    var companyCollectionResult = _userService.SyncGetCompanyService();
                    messageStr = companyCollectionResult.Error;
                    if (null != companyCollectionResult.Result)
                        messageStr = ResultEnumMessage(companyCollectionResult.Result.ResultExceptionk__BackingField);
                    if (!(string.IsNullOrEmpty(messageStr)))
                        AsynShowMessage(messageStr);
                    else
                    {
                        if (_waitBeforeLogin.InvokeRequired)
                            _waitBeforeLogin.BeginInvoke((EventHandler)delegate { _waitBeforeLogin.Caption = GlobalString.System_Config_String.LoginPassLoadingFolderStr; });
                        else
                            _waitBeforeLogin.Caption = GlobalString.System_Config_String.LoginPassLoadingFolderStr;

                        CacheGlobal.Add(GlobalString.System_Config_String.CompanyCollectionCache, companyCollectionResult.Result);
                        var folderCollectionResult = _userService.SyncGetFolderService();
                        messageStr = folderCollectionResult.Error;
                        if (null != folderCollectionResult.Result)
                            messageStr = ResultEnumMessage(folderCollectionResult.Result.ResultExceptionk__BackingField);
                        if (!(string.IsNullOrEmpty(messageStr)))
                            AsynShowMessage(messageStr);
                        else
                        {
                            if (_waitBeforeLogin.InvokeRequired)
                                _waitBeforeLogin.BeginInvoke((EventHandler)delegate { _waitBeforeLogin.Caption = GlobalString.System_Config_String.LoginPassLoadingFolderRoleStr; });
                            else
                                _waitBeforeLogin.Caption = GlobalString.System_Config_String.LoginPassLoadingFolderRoleStr;
                            CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, folderCollectionResult.Result);
                            var folderRoleCollectionResult = _userService.SyncGetFolderRoleService();
                            messageStr = folderRoleCollectionResult.Error;
                            if (null != folderRoleCollectionResult.Result)
                                messageStr = ResultEnumMessage(folderRoleCollectionResult.Result.ResultExceptionk__BackingField);
                            if (!(string.IsNullOrEmpty(messageStr)))
                                AsynShowMessage(messageStr);
                            else
                            {
                                CacheGlobal.Add(GlobalString.System_Config_String.FolderRoleCollectionCache, folderRoleCollectionResult.Result);
                                if (_waitBeforeLogin.IsHandleCreated)
                                    _waitBeforeLogin.BeginInvoke((EventHandler)delegate { _waitBeforeLogin.Close(); });
                                else
                                    _waitBeforeLogin.Close();
                                BeginInvoke((EventHandler)delegate
                                {
                                    txtLoginName.Text = "";
                                    txtPwd.Text = "";
                                    mainForm = new MainForm(this);
                                    mainForm.Show();
                                });
                                //      Thread.CurrentThread.Join();
                            }
                        }
                    }
                }
            }

        }
        #endregion

        #region Control event
        private void BtnLogin_Click(object sender, EventArgs e)
        {
            if (!IsHandleCreated)
                CreateHandle();
            if (string.IsNullOrEmpty(txtLoginName.Text.Trim()) || string.IsNullOrEmpty(txtPwd.Text.Trim()))
            {
                XtraMessageBox.Show(GlobalString.System_Exception_String.InputNullLoginStr, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var firstOrDefault = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault(x => x.AddressFamily.Equals(AddressFamily.InterNetwork));
                var loginArgs = new UserLoginArgs
                                    {
                                        UserNamek__BackingField = txtLoginName.Text,
                                        UserPassk__BackingField = CryptographyGlobal.Md5Encrypt(txtPwd.Text),
                                        LoginIpk__BackingField = firstOrDefault == null?"":firstOrDefault.ToString()
                                    };
            lock (lockObj)
            {
                _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.LoginLoadingStr,
                                      GlobalString.System_Config_String.LoadingPleaseWaitStr) { BackColor = BackColor, Width = 320 };
                _waitBeforeLogin.SuspendLayout();
                Hide();
                _waitBeforeLogin.Show();
            } 
            _userService.LoginService(loginArgs);

            //var loginThread = new Thread(() =>
            //                                 {

            //                                 }) {IsBackground = true};
            //loginThread.Start(); 
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void txtLoginName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            if (string.IsNullOrEmpty(txtLoginName.Text.Trim()))
            {
                loginNameTip.Show(string.Empty, txtLoginName, 0);
                loginNameTip.Show("请输入用户名!", txtLoginName);
            }
            else
            {
                if (string.IsNullOrEmpty(txtPwd.Text.Trim()))
                    txtPwd.Focus();
                else
                    BtnLogin_Click(BtnLogin, null);
            }
        }

        private void txtPwd_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            if (string.IsNullOrEmpty(txtPwd.Text.Trim()))
            {
                loginNameTip.Show(string.Empty, txtPwd, 0);
                loginNameTip.Show("请输入密码!", txtPwd);
            }
            else
            {
                if (string.IsNullOrEmpty(txtLoginName.Text.Trim()))
                {
                    txtLoginName.Focus();
                    loginNameTip.Show(string.Empty, txtLoginName, 0);
                    loginNameTip.Show("请输入用户名!", txtLoginName);
                }
                else
                    BtnLogin_Click(BtnLogin, null);
            }
        }

        private void Login_Move(object sender, EventArgs e)
        {
            loginNameTip.Hide(txtLoginName);
            loginNameTip.Hide(txtPwd);
        }

        private void Login_Paint(object sender, PaintEventArgs e)
        {
            loginNameTip.Hide(txtLoginName);
            loginNameTip.Hide(txtPwd);
        }

        private void txtLoginName_TextChanged(object sender, EventArgs e)
        {
            loginNameTip.Hide(txtLoginName);
            loginNameTip.Hide(txtPwd);
        }

        private void txtPwd_TextChanged(object sender, EventArgs e)
        {
            loginNameTip.Hide(txtLoginName);
            loginNameTip.Hide(txtPwd);
        }
        #endregion

        #region Public method
        private void AsynShowMessage(string message)
        {
            if (!IsHandleCreated)
                CreateHandle();
            if (_waitBeforeLogin.InvokeRequired)
                _waitBeforeLogin.BeginInvoke((EventHandler)delegate { _waitBeforeLogin.Close(); });
            else
                _waitBeforeLogin.Close();
            XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
            BeginInvoke((EventHandler)delegate
            {
                Show();
                if (!IsHandleCreated)
                    CreateHandle();
            });
        }

        private string ResultEnumMessage(BaseExceptionEnum exceptionEnum)
        {
            var result = string.Empty;
            switch (exceptionEnum)
            {
                case BaseExceptionEnum.GetCompanyCollectionException:
                    result = GlobalString.System_Exception_String.GetCompanyCollectionExceptionStr;
                    break;
                case BaseExceptionEnum.LogicException:
                    result = GlobalString.System_Exception_String.LogicExceptionStr;
                    break;
                case BaseExceptionEnum.UserNameOrPassError:
                    result = GlobalString.System_Exception_String.UserNameOrPassErrorStr;
                    break;
                case BaseExceptionEnum.AccountLock:
                    result = GlobalString.System_Exception_String.AccountLockStr;
                    break;
                case BaseExceptionEnum.GetFolderCollectionException:
                    result = GlobalString.System_Exception_String.GetFolderCollectionExceptionStr;
                    break;
                case BaseExceptionEnum.GetFolderRoleCollectionException:
                    result = GlobalString.System_Exception_String.GetFolderRoleCollectionExceptionStr;
                    break;
            }
            return result;
        }
        #endregion

    }
}
